package com.magicborrow.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.magicborrow.Constants;
import com.magicborrow.MagicBorrowApplication;


import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;


public class VolleyTool {
   /* public static Bitmap getHttpBitmap(Constants constants, String imgUrl) {
        getImageLoader().get(imgUrl, new ImageLoader.ImageListener() {
            @Override
            public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {

            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        return null;
    }*/


    public static RequestQueue getRequestQueue(Context context) {
        return MagicBorrowApplication.getInstance().getRequestQueue();
    }

    public static ImageLoader getImageLoader() {
        ImageLoader il = MagicBorrowApplication.getInstance().getImageLoader();
        return MagicBorrowApplication.getInstance().getImageLoader();
    }

    public static <T> void post(String url, final Map<String, String> params, final HTTPListener httpListener, int requestCode, Class<T> t) {
        doRequest(Request.Method.POST, url, params, httpListener, requestCode, t);
    }

    public static <T> void post(String url, JSONObject jsonBody, final HTTPListener httpListener, final int requestCode, final Class<T> t) {
        JsonObjectRequest jsonRequest = new JsonObjectRequest(
                url,
                jsonBody,
                new Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        System.out.println("请求返回数据" + response);
                        if (t != null) {
                            Gson gson = new Gson();
                            T obj = gson.fromJson(response.toString(), t);
                            httpListener.onResponse(obj, requestCode);
                        } else {
                            httpListener.onResponse(response.toString(), requestCode);
                        }
                    }
                }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Context context = MagicBorrowApplication.getInstance().getApplicationContext();
                Toast.makeText(context, VolleyErrorHelper.getMessage(error, context), Toast.LENGTH_LONG).show();
                httpListener.onErrorResponse(error, requestCode);
            }
        }) {
            @Override
            protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(
                            response.data, "UTF-8"));
                    return Response.success(jsonObject,
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }
            //			@Override
//			public Map<String, String> getHeaders()
//					throws AuthFailureError {
//				return getHeaderValue();
//			}
    };
        MagicBorrowApplication.getInstance().addToRequestQueue(jsonRequest);
    }

    public static <T> void get(String url, final Map<String, String> params, final HTTPListener httpListener, int requestCode, Class<T> t) {
        StringBuilder sb = new StringBuilder(url);
        if (params != null) {
            sb.append('?');
            for (Map.Entry<String, String> entry : params.entrySet()) {
                try {
                    sb.append(entry.getKey()).append('=')
                            .append(URLEncoder.encode(entry.getValue(), Constants.CODE_TYPE)).append('&');
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        System.out.println("get请求url" + sb.toString());
        doRequest(Request.Method.GET, sb.toString(), null, httpListener, requestCode, t);
    }

    private static <T> void doRequest(int type, String url, final Map<String, String> params, final HTTPListener httpListener, final int requestCode, final Class<T> t) {
        StringRequest postRequest = new StringRequest(
                type,
                url,
                new Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            response = new String(response.getBytes(), "utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        System.out.println("请求返回数据" + response);
                        if (t != null) {
                            Gson gson = new Gson();
                            T obj = gson.fromJson(response, t);
                            httpListener.onResponse(obj, requestCode);
                        } else {
                            httpListener.onResponse(response, requestCode);
                        }
                    }
                }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Context context = MagicBorrowApplication.getInstance().getApplicationContext();
                Toast.makeText(context, VolleyErrorHelper.getMessage(error, context), Toast.LENGTH_LONG).show();
                httpListener.onErrorResponse(error, requestCode);
            }
        }) {
            @Override
            protected Map<String, String> getParams()
                    throws AuthFailureError {
                return params;
            }

//			@Override
//			public Map<String, String> getHeaders()
//					throws AuthFailureError {
//				return getHeaderValue();
//			}
        };
        MagicBorrowApplication.getInstance().addToRequestQueue(postRequest);
    }

//	private static Map<String,String> getHeaderValue(){
//		Map<String,String> headers = new HashMap<String,String>();
//		String token = "YG.USFood.ANDROID.AAAAB3NzaC1yc2EAAAABIwAAAQEAwEtF1hfvsOpIboYO01g1D0ZOVPm1p";
//		String timestamp = System.currentTimeMillis()+"";
//		Random rd = new Random();
//		int ad = rd.nextInt(10000);
//		String nonce = ad+"";
//		String[] columns = new String[] { token, timestamp, nonce };
//		Arrays.sort(columns);
//		String singature = convertSHA1(TextUtils.join("", columns));
//		headers.put("YgUsFood", "signature="+singature
//				+"&timestamp="+timestamp+"&nonce="+nonce);
//		return headers;
//	}

//	private static String convertSHA1(String plainText) {
//		String result = "";
//		try {
//			MessageDigest md = MessageDigest.getInstance("SHA-1");
//			md.update(plainText.getBytes());
//			byte bg_order_manage[] = md.digest();
//			int i;
//			StringBuffer buf = new StringBuffer("");
//			for (int offset = 0; offset < bg_order_manage.length; offset++) {
//				i = bg_order_manage[offset];
//				if (i < 0)
//					i += 256;
//				if (i < 16)
//					buf.append("0");
//				buf.append(Integer.toHexString(i));
//			}
//			result = buf.toString();
//			//System.out.println("result32: " + buf.toString());// 32位的加密
//			//System.out.println("result16: " + buf.toString().substring(8, 24));// 16位的加密
//		} catch (NoSuchAlgorithmException e) {
//			e.printStackTrace();
//
//		}
//		return result;
//	}


    public interface HTTPListener {
        <T> void onResponse(T t, int requestCode);

        void onErrorResponse(VolleyError error, int requestCode);
    }
}
